/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-17 19:17:30
 ******************************************************************************/
package cn.cmcc.online.smsapi.sdk.db.entity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.content.ContentValues;
import cn.cmcc.online.smsapi.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.DBManager;
import cn.cmcc.online.smsapi.sdk.db.XyCursor;
import cn.cmcc.online.smsapi.sdk.db.base.BaseManager;
import cn.cmcc.online.smsapi.sdk.dex.DexUtil;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.util.StringUtils;
import cn.cmcc.online.smsapi.sdk.util.XyUtil;

/* SDK-500 huangzhiqiang 20160621 start */

public class NetQueryTimeManager {

    public static final String TABLE_NAME = "tb_netquery_time";
    public static final String DROP_TABLE = " DROP TABLE IF EXISTS " + TABLE_NAME;

    public static final String id = "id";

    public static final String phone_num = "phone_num";
    public static final String AREA_CODE = "area_code";
    public static final String request_time = "request_time";
    /* SDK-500 huangzhiqiang 20160621 start */
    public static final String status = "status"; // 状态（ 0:已请求 1:有返回数据）
    /* SDK-500 huangzhiqiang 20160621 end */

    public static final String ADD_AREACODE = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + AREA_CODE + " TEXT";

    /* SDK-500 huangzhiqiang 20160621 start */
    public static final String ADD_STATUS = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + status + " INTEGER DEFAULT 0";
    /* SDK-500 huangzhiqiang 20160621 end */

    public static String getCreateTableSql() {
        return " create table  if not exists " + TABLE_NAME + " (" + id + " INTEGER PRIMARY KEY," + phone_num
                + " TEXT," + AREA_CODE + " TEXT," + request_time+ " LONG DEFAULT 0," + status+ " INTEGER DEFAULT 0)";
    }

    /**
     * 添加/更新号码联网查询记录
     * 
     * @param phoneNum
     * @param areaCode
     * @param status 状态（ 0:已请求 1:有返回数据）
     * @return
     */
    public static long insertOrUpdateNetQueryTime(String phoneNum, String areaCode, int status) {
        /* SDK-538 huangzhiqiang 20160714 start */
        return insertOrUpdateNetQueryTime(phoneNum, areaCode, status, System.currentTimeMillis());
        /* SDK-538 huangzhiqiang 20160714 start */
    }

    /* SDK-538 huangzhiqiang 20160714 start */
    public static long insertOrUpdateNetQueryTime(String phoneNum, String areaCode, int status, long requestTime) {
        long result = -1;
        ContentValues values = null;
        try {
            /* SDK-500 huangzhiqiang 20160621 start */
            values = BaseManager.getContentValues(null, AREA_CODE, areaCode, phone_num, phoneNum, request_time,
                    String.valueOf(requestTime), NetQueryTimeManager.status, String.valueOf(status));

            /* SDK-500 huangzhiqiang 20160621 start */

            int rows = DBManager.update(TABLE_NAME, values, phone_num + " = ? and " + AREA_CODE + " = ?", 
                    new String[] { phoneNum, areaCode });
            if (rows <= 0) {
                result = DBManager.insert(TABLE_NAME, values);
            } else {
                result = 0;
            }
        } catch (Throwable e) {
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "insertOrUpdateNetQueryTime: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
        return result;
    }
    /* SDK-538 huangzhiqiang 20160714 end */
    
    private static JSONObject queryInfoByPhoneNum(String phoneNum, String areaCode) {
        XyCursor cur = null;
        JSONObject info = null;
        try {
            final String[] mColumns = new String[] { id, phone_num, request_time };
            cur = DBManager.query(TABLE_NAME, mColumns, phone_num + " = ? and " + AREA_CODE + " = ?", new String[] { phoneNum, areaCode }, null, null, null, "1");
            info = BaseManager.loadSingleDataFromCursor(mColumns, cur);
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "queryInfoByPhoneNum: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(cur, true);
        }
        return info;
    }

    public static boolean isAllowQuery(String phoneNum, String areaCode, boolean hasData) {
        try {
            int type = XyUtil.checkNetWork(Constant.getContext(), 2);
            if (type == -1) {
                return false;
            }
            JSONObject json = queryInfoByPhoneNum(phoneNum, areaCode);

            if (json != null) {
                /* SDK-500 huangzhiqiang 20160621 start */
                long lastRequestTime = Long.parseLong(json.getString(request_time));
                // 与批量更新周期一致
                long queryCycle = DexUtil.getUpdateCycleByType(
                        OnlineUpdateCycleConfigInterface.TYPE_BATCH_PUBLIC_NUM_INFO_UPDATE_CYCLE, Constant.month);
                if (System.currentTimeMillis() > lastRequestTime + queryCycle) {
                    // 更新号码联网查询时间并将状态设置为已请求
                    insertOrUpdateNetQueryTime(phoneNum, areaCode, 0);
                    return true;
                } else {
                    return false;
                }
                /* SDK-500 huangzhiqiang 20160621 end */
            } else {
                /* SDK-500 huangzhiqiang 20160621 start */
                // 记录号码联网查询时间并将状态设置为已请求
                insertOrUpdateNetQueryTime(phoneNum, areaCode, 0);
                /* SDK-500 huangzhiqiang 20160621 end */
                return true;
            }
        } catch (Throwable e) {
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "isAllowQuery: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
        return true;
    }

    /* SDK-500 huangzhiqiang 20160621 start */
    /**
     * 获取已联网请求但无企业资料数据返回的号码
     * 
     * @param areaCode
     * @param periodTime
     * @return
     */
    public static List<String> getUnKnowNum(String areaCode, long periodTime) {
        // status=0为已请求但没有数据的号码
        return getNetQueryNum(areaCode, periodTime, 0);
    }
    /* SDK-500 huangzhiqiang 20160621 end */

    /**
     * 获取超过周期时间未更新的号码列表
     * 
     * @param areaCode
     * @param periodTime 返回该时间之前的数据
     * @param status 状态（ 0:已请求 1:有返回数据 -1:所有数据）
     * @return
     */
    public static List<String> getNetQueryNum(String areaCode, long periodTime, int status) {

        XyCursor cur = null;
        try {
            /* SDK-384 huangzhiqiang 20160411 start */
            /* SDK-397 huangzhiqiang 20160528 start */
            /* SDK-500 huangzhiqiang 20160621 start */
            /* SDK-478 huangzhiqiang 20160628 start */
            String sql = "SELECT DISTINCT tbA.phone_num FROM tb_netquery_time tbA  WHERE tbA.request_time<? AND tbA.request_time>0";
            /* SDK-478 huangzhiqiang 20160628 end */

            List<String> selectionArgs = new ArrayList<String>(); 
            selectionArgs.add(String.valueOf(periodTime));

            if (status != -1) {
                sql += " AND tbA.status=?";
                selectionArgs.add(String.valueOf(status));
            }
            if (!StringUtils.isNull(areaCode)) {
                sql += " AND tbA.area_code=?";
                selectionArgs.add(areaCode);
            }
            cur = DBManager.rawQuery(sql, selectionArgs.toArray(new String[selectionArgs.size()]));
            /* SDK-500 huangzhiqiang 20160621 end */
            /* SDK-397 huangzhiqiang 20160528 end */
            /* SDK-384 huangzhiqiang 20160411 end */
            if (cur == null) {
                return null;
            }
            List<String> resList = new ArrayList<String>();
            while (cur.moveToNext()) {
                JSONObject obj = new JSONObject();
                obj.put("num", cur.getString(0));
                obj.put("version", "-1");
      
                resList.add(obj.toString());
            }
            return resList;
        } catch (Throwable e) {
            /*SDK-550 hewengao 20160719 start*/
            LogManager.e(Constant.TAG, "getNetQueryNum: " , e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(cur, true);
        }
        return null;
    }

    public static void delNetQueryNum(String phoneNum, String areaCode) {
        try {
            if (StringUtils.isNull(phoneNum)) {
                return;
            }
            String where = " phone_num = ? ";
            if (!StringUtils.isNull(areaCode)) {
                where += " and " + AREA_CODE + " = '" + areaCode + "'";
            }
            int rows = DBManager.delete(TABLE_NAME, where, new String[] { phoneNum });
        } catch (Throwable e) {
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w("NetQueryTimeManager", "delNetQueryNum error: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
    }

    public static void setUpdateUnKnowNumTime(long periodTime) {
        try {
            ContentValues values = new ContentValues();
            values.put(request_time, System.currentTimeMillis());
            /* SDK-500 huangzhiqiang 20160621 start */
            DBManager.update(TABLE_NAME, values, request_time + " < ? and request_time > 0 AND " + status + " = 0",
                    new String[] { String.valueOf(periodTime) });
            /* SDK-500 huangzhiqiang 20160621 end */
        } catch (Throwable e) {
            // TODO Auto-generated catch block
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.e("NetQueryTimeManager", "clearUpdateUnKnowNumTime error: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
    }
}
